//
//  File.swift
//  NetWork
//
//  Created by Delin Meng 孟德林 on 2018/11/27.
//  Copyright © 2018 Delin Meng 孟德林. All rights reserved.
//

import Foundation

/// FD文件管理器异常
public enum FDFileError: Error {
    case creatFailed
    /// 写文件失败
    case writeFailed(_ reason: WriteFailureReason)
    /// 读文件失败
    case readFailed(_ reason: ReadFailureReason)
    /// 读文件失败
    case fetchFileAttributeFailed(_ attribute: String)

    /// 写文件失败原因
    public enum WriteFailureReason {
        /// 创建文件夹失败
        case createDirectoryFailed(_ path: String, _ error: Error)
        /// 创建文件失败
        case createFileFailed(_ path: String, _ error: Error)
        /// 字符串无法转换成 Data
        case stringToDataFailed(_ path: String)
    }

    /// 读文件失败原因
    public enum ReadFailureReason {
        /// 文件不存在
        case fileNotExists(_ path: String)
        /// filehandle 初始化失败
        case fileHandleInitFailed(_ path: String)
        /// Data 无法转换成 String
        case dataToStringFailed(_ path: String)
    }
}

extension FDFileError: LocalizedError {

    /// 遵循 LocalizedError 实现 errorDescription 可以使外部统一从 error.localizedDescription 获取错误信息
    public var errorDescription: String?{
        switch self {
        case .creatFailed:
            return "[创建文件失败]\n"
        case .writeFailed(let reason):
            return reason.localizedDescription
        case .readFailed(let reason):
            return reason.localizedDescription
        case .fetchFileAttributeFailed(let key):
            return "[获取文件属性失败]\nKey: \(key)"
        }
    }
}

extension FDFileError.WriteFailureReason {
    var localizedDescription: String {
        switch self {
        case .createDirectoryFailed(let path, let error):
            return "[写文件失败]\nPath：\(path)\n创建文件夹失败，异常原因：\(error.localizedDescription)"
        case .createFileFailed(let path, let error):
            return "[写文件失败]\nPath：\(path)\n创建文件失败，异常原因：\(error.localizedDescription)"
        case .stringToDataFailed(let path):
            return "[写文件失败]\nPath：\(path)\n创建文件失败，异常原因：字符串无法 utf8 编码成 Data"
        }
    }
}

extension FDFileError.ReadFailureReason {
    var localizedDescription: String {
        switch self {
        case .fileNotExists(let path):
            return "[读文件失败]\nPath：\(path)\n异常原因: 文件不存在"
        case .fileHandleInitFailed(let path):
            return "[读文件失败]\nPath：\(path)\n异常原因: file handle 初始化失败，因为文件不存在"
        case .dataToStringFailed(let path):
            return "[读文件失败]\nPath：\(path)\n异常原因: Data 无法转换成 String"
        }
    }
}

